package com.org.captcha;

import com.google.code.kaptcha.Producer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import org.slf4j.Logger;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@RestController
@AllArgsConstructor
@Slf4j
public class CaptchaController {
    private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    private final Producer kaptchaProducer;

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        try {
            // 生成验证码文本
            String captchaText = kaptchaProducer.createText();
            // 将验证码文本存入session
            session.setAttribute("captcha", captchaText);

            // 生成验证码图片
            BufferedImage image = kaptchaProducer.createImage(captchaText);

            // 设置响应头，防止缓存
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);

            // 设置响应内容类型为图片
            response.setContentType("image/png");

            // 输出图片流
            ImageIO.write(image, "png", response.getOutputStream());
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("生成验证码失败", e);
            throw new RuntimeException("生成验证码失败", e);
        }
    }
}
